package com.prometheus.util;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author: Alan
 * @date: 2021/5/22 15:18
 */
public class SemaphoreTest {

    static ExecutorService pool =  Executors.newCachedThreadPool();
    static Semaphore semaphore = new Semaphore(3,true);

    public static void semaphoreTest() {
        for (int i = 0; i < 10; i++) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();//获取信号灯许可
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Thread "+Thread.currentThread().getName()+" 进入" +"当前系统的并发数是："+(3-semaphore.availablePermits()));
                    try {
                        Thread.sleep(new Random().nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Thread "+Thread.currentThread().getName()+" 即将离开");
                    semaphore.release();//释放信号灯
                    System.out.println("Thread "+Thread.currentThread().getName()+" 已经离开，当前系统的并发数是："+(3-semaphore.availablePermits()));
                }
            };
            pool.execute(runnable);

        }
    }

    public static void main(String[] args) {

        System.out.println("main semaphoreTest before availablePermits :" + semaphore.availablePermits());
        semaphoreTest();
        try {
            System.out.println("main semaphoreTest after availablePermits :" + semaphore.availablePermits());
            Thread.sleep(5000);
            System.out.println("main release before availablePermits :" + semaphore.availablePermits());
            //添加一个信息号
            semaphore.release();
            Thread.sleep(5000);
            System.out.println("main release after availablePermits :" + semaphore.availablePermits());
            //删除一个信息号
            semaphore.acquire();
            System.out.println("main acquire after availablePermits :" + semaphore.availablePermits());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
